This unit continues the evaluation story from Unit 24, now introducing extrinsic
clustering evaluation measures — Purity,
the Rand Index,
and the Jaccard Coefficient —
then switches to a fundamentally different clustering algorithm:
DBSCAN.
We will see how DBSCAN discovers clusters of arbitrary shape and explicitly flags
noise/outlier points, and we will study how to select its hyperparameters MinPts and
\( \varepsilon \) (epsilon) via the K-distance graph.
Learning Objectives
Compute Purity of a clustering given a cluster × label contingency table
Calculate TP, TN, FP, FN counts on pairwise agreements and derive Rand Index & Jaccard
List and define the three DBSCAN point types: core, border, noise
State DBSCAN's core definitions: directly density-reachable, density-reachable, density-connected
Manually execute DBSCAN on a small 2D dataset given MinPts and ε
Use the rule-of-thumb for MinPts (≥ d+1) and the K-distance elbow method to tune ε
Compare DBSCAN vs K-Means across 8+ dimensions: K-choice, shape, outliers, etc.
Today's Agenda
Recap of Silhouette Coefficient & average silhouette width
For each object \( d_i \in C_i \), compute its per-cluster average silhouette width:
\[
\bar{s}(C_j) = \frac{1}{|C_j|} \sum_{d_i \in C_j} s(i)
\]
and the global average silhouette width:
\[
\text{ASW} = \frac{1}{n} \sum_{i=1}^{n} s(i)
\]
Computationally, silhouette is expensive for large datasets (O(n²) distance evaluations).
2.2 Extrinsic Clustering Evaluation Measures
Extrinsic measures require ground-truth labels and compare a generated clustering
against these labels. They enable head-to-head comparison of algorithms on benchmark
datasets where labels exist. We cover three: Purity, Rand Index, Jaccard.
Purity
Rand Index (RI)
Jaccard Coefficient
Intuition: For each cluster, count the frequency of the most common true class inside it. Sum these maxima and divide by n.
where \( C_i \) = i-th produced cluster, \( L_j \) = j-th ground-truth label class.
Range: [0, 1]. Higher = better.
Problem: Purity monotonically improves with more clusters — setting K=n achieves Purity=1 trivially (each point its own cluster; max count =1 every time). Use it alongside other measures.
Intuition: Over ALL pairs of points in the dataset, count whether clustering and ground truth AGREE on whether they belong together.
For any pair of distinct points (p, q):
TP (True Positive): clustering puts them together AND labels put them together.
TN (True Negative): clustering separates them AND labels separate them.
FP (False Positive): clustering puts them together BUT labels separate them.
FN (False Negative): clustering separates them BUT labels put them together.
Range [0, 1]. Higher = more agreement. Dominated by TN when data is imbalanced (most pairs belong to different classes). Adjusted Rand Index (ARI) corrects for chance and is preferred in practice.
Intuition: Set-based overlap that IGNORS true negatives — only cares about pairs that at least one method puts together.
2.5 DBSCAN — Density-Based Spatial Clustering of Applications with Noise
DBSCAN classifies every data point into exactly one of three categories, based
on two hyperparameters: the radius ε (epsilon) and the neighbor count MinPts.
1. Core Points
2. Border Points
3. Noise Points
A point q is a core point if its ε-neighborhood contains at least MinPts points (counting q itself).
Property: Core points lie in the interior of a dense region. They are the "seeds" from which clusters are grown.
A point p is a border point if its own ε-neighborhood has < MinPts, BUT there exists a chain of direct density-reachability links from a core point to p.
Property: Border points sit on the edge of a dense region. They belong to a cluster but cannot extend it further.
A point is a noise point (outlier) if it is neither a core point nor reachable from any core point.
Property: Noise points are explicitly assigned a cluster label of −1 in sklearn. This is the only one of the three algorithms studied that allows "not in any cluster."
2.6 DBSCAN Key Definitions
Directly density-reachable: p is directly density-reachable from q if:
q is a core point, AND
p is within ε of q (p ∈ N_ε(q)).
Note: "directly reachable" is NOT symmetric. A core can reach a border, but a border cannot reach back because borders aren't core points.
Density-reachable: p is density-reachable from q if there exists a chain of
points q → q₁ → q₂ → … → q_k → p such that each adjacent step is directly density-reachable.
Still asymmetric in general.
Density-connected: p and q are density-connected if there exists some core point o such that BOTH p and q are density-reachable from o.
Symmetric! Captures the "same cluster" relationship.
A DBSCAN cluster: A maximal set of density-connected points.
Step 0: Find cores. For each point, count its ε-neighbors (distance ≤ 2):
A(1,4): dist to B = √((1)²+(-1)²)=√2≈1.41; to C=√(0+1)=1.0; to D=√16+1≈4.12; to E≈√58≈7.6. Neighborhood: {A,B,C} (size 3 ≥ 2). → A is CORE.
B(2,3): to A≈1.41, to C=√(1+4)=√5≈2.24 >2, to D≈3.6, to E≈6.3. Neighborhood: {B,A} (size 2 ≥ 2). → B is CORE? Actually count includes B itself = 2 → Yes, CORE.
C(1,5): to A=1.0, to B≈2.24, to D≈4.0. Neighborhood: {C,A}=2 → CORE.
D(5,5): to A≈4.12, to B≈3.6, to C≈4.0, to E≈5.0. Neighborhood: {D}=1 < 2 → NOT core.
E(8,1): distances huge. Only itself → NOT core.
Step 1: Grow clusters from cores.
Start with core A → Create Cluster 1. Add A. Expand to B (directly reachable) and C (directly reachable). Done (B and C, while cores, have no new points within ε).
D has no other neighbors besides itself → mark as noise.
E has no other neighbors besides itself → mark as noise.
Point
Coordinates
Type
Final Label
A
(1, 4)
Core
Cluster 1
B
(2, 3)
Core
Cluster 1
C
(1, 5)
Core
Cluster 1
D
(5, 5)
Noise
−1 (noise)
E
(8, 1)
Noise
−1 (noise)
2.8 Selecting DBSCAN Hyperparameters
Selecting MinPts
Rule of thumb: MinPts ≥ (dimensionality + 1), where d = number of features.
For 2D data: MinPts ≥ 3 (common pick: 4).
For higher dimensions: MinPts ≥ 4 or 5 as a start.
Larger MinPts:
More robust to noise/outliers.
May merge smaller dense patches (loss of granularity).
Standard starting heuristic: MinPts = 4 or 5, then tune.
Selecting ε via the K-Distance Graph
For each point in the dataset, compute the distance to its k-th nearest neighbor,
with k = MinPts (or k = MinPts − 1 depending on convention). Then sort all these
k-distances in ASCENDING order and plot. Use the elbow of this curve as ε.
Points in dense regions (cluster members): k-th nearest neighbor is close → small k-distance.
Points in sparse regions (outliers / noise): k-th nearest neighbor is far → large k-distance.
Elbow: transition region where distances "jump" from small (inliers) to large (outliers). Choose ε at that jump.
Iris K-distance Graph Case Study
With eps=0.2 and MinPts=5 on scaled Iris: all points become noise (label=-1) → ε is too small.
Using k-distance elbow method on Iris (k ≈ MinPts−1): pick ε ≈ 0.8 at the bend.
Running DBSCAN with ε=0.8, MinPts=5: two clusters discovered with very few noise points.
Why 2 clusters instead of 3? PCA visualization of Iris confirms two major dense regions in feature space; Setosa is well-separated from Versicolor + Virginica which partially overlap.
2.9 DBSCAN vs K-Means: Side-by-Side
Aspect
K-Means
DBSCAN
Requires K specified beforehand?
Yes
No (discovers K automatically from density structure)
Assumes spherical / convex clusters?
Yes (centroid + SSE)
No (finds arbitrarily shaped clusters — even nested / crescent shapes)
Sensitive to outliers?
Very (outliers pull centroids toward them)
Robust (explicitly marks outliers as noise / −1)
Forces every point into a cluster?
Yes (hard assignment)
No (points can remain as noise)
Struggles with arbitrary / non-convex shapes?
Yes (splits them unnaturally)
Excellent at non-convex and nested shapes
Memory usage
Low
Needs distance matrix or spatial index (can be high)
Speed / Scalability
Very fast (linear in n × iter)
Slower (range queries needed)
Interpretable cluster centers?
Yes (centroids are meaningful)
No real "center" (harder to explain to business stakeholders)
3. Interactive Examples
Example 1: Purity of "one cluster per point"
A student claims "I can always achieve perfect purity, regardless of the dataset."
Is this possible? If yes, construct it. If not, explain.
Yes, trivially: set K = n (each point its own singleton cluster).
In each singleton cluster, the single point has exactly one true label, so
max_j |C_i ∩ L_j| = 1 for every cluster. Sum of maxima = n, so Purity = n/n = 1.
This is precisely why purity alone is misleading: it rewards you for infinite K.
Always use it in combination with Adjusted Rand Index, Silhouette, or metrics
that penalize more clusters.
Example 2: DBSCAN MinPts Intuition
A 7-dimensional dataset is to be clustered with DBSCAN. Which MinPts value is the
most reasonable starting point: 1, 2, 4, or 100?
Reveal Answer
MinPts = 4. The rule of thumb: MinPts ≥ d+1 = 8, but 4 is close and a
standard starting value (MinPts ≥ 4 or 5 for high dim).
Why not the others?
MinPts = 1: every point is its own "core" → degenerate; every point forms its own cluster / no structure.
MinPts = 2: borderline; very sensitive to noise.
MinPts = 100: too large — many truly dense regions will have fewer than 100 neighbors within any reasonable ε → everything becomes noise.
Example 3: K-Means vs DBSCAN on two moons
The classic "two interleaved half-moons" dataset has two non-convex crescent-shaped
clusters. Which algorithm will recover the two moons correctly, and why?
DBSCAN will recover the two moons perfectly (with appropriate MinPts and ε):
Each crescent is a uniformly dense region → within each moon, every interior point is a core; the entire crescent is density-connected.
Between the two crescents there's a gap → no density bridge → DBSCAN correctly separates them into two clusters.
K-Means with K=2 will fail: it splits each crescent through the middle and produces two "half-moon sliced" clusters, because the centroids migrate to the overall arithmetic means of each half of the plane, which don't respect the shape.
Example 4: Rand Index edge case — perfect clustering
True labels: 4 points form 2 natural classes. Clustering produced also 2 clusters
identical to the true classes. What is the Rand Index? (Compute explicitly.)
Reveal Answer
Points: p1,p2 in L1; p3,p4 in L2. Same for clusters C1={p1,p2}, C2={p3,p4}.
As expected: perfect clustering has Rand Index = 1.
4. Numerical Solutions
Problem 1: Purity from 3×2 contingency table
Contingency table (rows = produced clusters, cols = true labels):
Cluster
Label X
Label Y
Total
C1
8
2
10
C2
3
7
10
C3
5
5
10
Label total
16
14
n = 30
Compute Purity.
📘 Step-by-Step Solution
Step 1: Per-cluster max class count.
C1: max(8,2) = 8
C2: max(3,7) = 7
C3: max(5,5) = 5 (ties broken arbitrarily since value is same)
Step 2: Sum of maxima = 8 + 7 + 5 = 20.
Step 3: Divide by n:
\[
\text{Purity} = \frac{20}{30} \approx 0.667
\]
Problem 2: DBSCAN class identification
Six 1D points on a number line at positions: {1, 2, 3, 6, 10, 11}.
Use MinPts=3 and ε=1.2 (distance = absolute difference).
Classify each point as Core / Border / Noise. Then list the clusters found.
📘 Step-by-Step Solution
Step 1: For each point, count points within ε=1.2 (including itself).
Point
Pos
Neighbors (|x − pos| ≤ 1.2)
Count
Core?
p1
1
{1,2}
2 < 3
No
p2
2
{1,2,3}
3 ≥ 3
✅ YES CORE
p3
3
{2,3}
2 < 3
No
p4
6
{6}
1 < 3
No
p5
10
{10,11}
2 < 3
No
p6
11
{10,11}
2 < 3
No
Step 2: Find border vs noise. p2 is the only core.
p1 is within ε of core p2 (|1−2|=1 ≤ 1.2) → Border of the same cluster.
p3 is within ε of core p2 (|3−2|=1 ≤ 1.2) → Border.
p4: not a core AND distance to nearest core (p2) = 4 > 1.2 → no core can reach it → Noise.
Interpretation: Rand 0.5 is essentially random-level agreement on this tiny dataset. Jaccard 0 because the produced clustering put no pair together that should have been together.
5. Try It Yourself
Practice 1: Purity calculation 2×3
Contingency table (clusters × labels):
Red
Green
Blue
Total
Cluster A
9
1
1
11
Cluster B
1
8
5
14
Total
10
9
6
25
Compute Purity. Round to 3 decimals.
Max row A = max(9,1,1) = 9.
Max row B = max(1,8,5) = 8.
Sum = 17. n = 25.
\[
\text{Purity} = \frac{17}{25} = 0.680
\]
Practice 2: DBSCAN MinPts=4
2D points: A(0,0), B(1,0), C(0,1), D(1,1), E(5,5). ε=1.5, MinPts=4.
Classify each point and describe resulting clusters.
ε-radius around each point:
A: N includes A,B,C,D (distances: 0, 1, 1, √2 ≈ 1.41 ≤ 1.5) → 4 points ≥ 4 → Core.
B: neighbors: A, B, D, C (same distances) → 4 → Core.
C: neighbors: A, C, D, B (same) → 4 → Core.
D: neighbors: A, B, C, D → 4 → Core.
E(5,5): distance to nearest others is √((5−1)²+(5−1)²) ≈ 5.66 > 1.5 → only itself in ε-neighborhood. NOT core. Not reachable from any core. → Noise.
Result: One cluster = {A,B,C,D}. E is noise (−1).
Practice 3: Adjusted Rand intuition via Rand baseline
We'll skip the exact ARI formula in this course, but explain qualitatively:
If RI = 0.86 on a dataset, why might the Adjusted Rand Index ARI be only 0.58,
and why do we prefer the adjusted version?
The plain Rand Index is dominated by TN (pairs that both methods put in different
groups). In typical datasets with many classes, MOST pairs are in different true
classes, and MOST pairs are also in different clusters — so even random clusterings
can have a high Rand index merely by "mostly saying no."
The Adjusted Rand Index (ARI) corrects this by subtracting the expected RI
under a random-partition baseline and normalizing, so that ARI ≈ 0 for random
independent partitions and ARI = 1 only for perfect agreement. This is why ARI
(and not plain RI) is the standard in scikit-learn's
adjusted_rand_score.
6. Interactive Quiz
Your score: 0 / 5
7. Key Takeaways
Purity = 1/n Σ max_j |C_i ∩ L_j|, but it improves monotonically with K — not a standalone metric.
Rand Index = (TP + TN) / (all C(n,2) pairs) measures pairwise agreement between clustering and labels. Jaccard = TP/(TP+FP+FN) ignores TN and emphasizes positive agreement.
DBSCAN has 3 point types: Core (≥ MinPts in ε-ball), Border (in a core's ε-ball but not a core), Noise (−1, everything else).
DBSCAN key relationships: directly density-reachable (core→within ε), density-reachable (chain of direct), density-connected (mutually reachable from some core, symmetric → defines cluster).
Set MinPts ≥ d+1 (typically 4 or 5). Set ε from the elbow of the sorted k-distance (k ≈ MinPts) curve where dense regions transition to sparse outliers.
DBSCAN auto-discovers K, handles arbitrary shapes and marks outliers explicitly; K-Means requires K, assumes spherical clusters, and forces every point into a cluster.
8. Common Pitfalls
Purity as the sole metric: K=n always gives Purity=1. Always cross-check with RI/ARI and silhouette or run at a fixed K chosen via domain constraints.
Forgetting to count the point ITSELF in MinPts: "ε-neighborhood size ≥ MinPts" includes the query point. A point with 2 other neighbors within ε counts MinPts=3, not 2.
Misunderstanding "directly density-reachable" as symmetric: It's not. A border point is within ε of a core (core→border is "direct"), but the reverse step is invalid because the border is not itself a core.
Running DBSCAN on unscaled data: ε is a Euclidean radius, so feature scales matter. StandardScaler / MinMaxScaler first.
Picking ε too small / too large: Too small → almost everything is noise (−1); too large → all dense points merge into one giant cluster. Use the K-distance elbow, never guess.
Rand Index dominance by TNs: With many classes, TN dominates RI, making random-looking splits score high anyway. Prefer ARI.